<template>
  <div class="register-container">
    <!-- 顶部图标区域 -->
    <div class="register-header">
      <img src="../assets/logo.png" alt="Logo" class="logo">
      <h1>用户注册</h1>
      <p class="subtitle">加入饿了么外卖平台</p>
    </div>

    <!-- 注册表单区域 -->
    <div class="register-form">
      <div class="form-group">
        <div class="input-with-icon">
          <i class="fa fa-user"></i>
          <input 
            type="text" 
            v-model="user.username" 
            placeholder="请输入用户名/昵称"
            class="form-input"
            @blur="checkUsername" 
          />
        </div>
        <div v-if="usernameError" class="error-message">
          {{ usernameError }}
        </div>
      </div>
      
      <div class="form-group">
        <div class="input-with-icon">
          <i class="fa fa-mobile"></i>
          <input 
            type="text" 
            v-model="user.phoneNumber" 
            placeholder="请输入11位手机号"
            class="form-input"
            maxlength="11"
            @input="validatePhoneNumber"
            @blur="checkPhoneNumber" 
          />
        </div>
        <div v-if="phoneError" class="error-message">
          {{ phoneError }}
        </div>
      </div>
      
      <div class="form-group">
        <div class="input-with-icon">
          <i class="fa fa-lock"></i>
          <input 
            type="password" 
            v-model="user.password" 
            placeholder="请输入密码"
            class="form-input" 
          />
        </div>
      </div>
      
      <div class="form-group">
        <div class="input-with-icon">
          <i class="fa fa-check-circle"></i>
          <input 
            type="password" 
            v-model="confirmPassword" 
            placeholder="请再次输入密码"
            class="form-input" 
          />
        </div>
      </div>

      <div class="form-group gender-group">
        <label class="gender-label">性别：</label>
        <div class="gender-options">
          <label class="gender-option">
            <input type="radio" v-model="userSex" value="1" />
            <span class="radio-button"></span>
            <span class="radio-label">男</span>
          </label>
          <label class="gender-option">
            <input type="radio" v-model="userSex" value="0" />
            <span class="radio-button"></span>
            <span class="radio-label">女</span>
          </label>
        </div>
      </div>

      <button @click="register" class="register-button">
        <span v-if="!isLoading">注册</span>
        <span v-else class="loading-spinner">
          <i class="fa fa-spinner fa-spin"></i>
        </span>
      </button>
      
      <div class="login-link">
        <span>已有账号?</span>
        <a @click="goToLogin" class="login-button">立即登录</a>
      </div>
    </div>

    <!-- 用户协议部分 -->
    <div class="agreement">
      <input type="checkbox" id="agree" v-model="agreeTerms">
      <label for="agree">我已阅读并同意<a href="#">《用户协议》</a>和<a href="#">《隐私政策》</a></label>
    </div>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import Footer from "../components/Footer.vue";
import { useRouter, useRoute } from "vue-router";
import { ref } from "vue";
import { userApi } from '@/api';

const router = useRouter();
const route = useRoute();

// 用户信息 - 适配Spring Security的User模型
const user = ref({
  username: "",  // 用户名，作为显示名称
  password: "",  // 密码
  phoneNumber: "", // 手机号，用于登录
  activated: true, // 用户激活状态
  // 不要在这里设置authorities，我们会在注册时正确构造
});
const confirmPassword = ref("");
const userSex = ref("1");  // 性别单独存储，1-男，0-女
const phoneError = ref("");  // 用于显示手机号错误信息
const usernameError = ref("");  // 用于显示用户名错误信息
const isLoading = ref(false);  // 用于显示加载状态
const agreeTerms = ref(false); // 用于勾选用户协议

// 实时验证手机号格式
const validatePhoneNumber = () => {
  const phone = user.value.phoneNumber;
  
  // 清除之前的错误
  phoneError.value = "";
  
  // 如果为空，不显示错误
  if (!phone) return;
  
  // 检查是否只包含数字
  if (!/^\d*$/.test(phone)) {
    phoneError.value = "手机号只能包含数字";
    // 清除非数字字符
    user.value.phoneNumber = phone.replace(/\D/g, '');
    return;
  }
  
  // 检查长度
  if (phone.length > 0 && phone.length < 11) {
    phoneError.value = "手机号需要11位数字，当前: " + phone.length + "位";
  }
};

// 检查手机号是否已存在
const checkPhoneNumber = async () => {
  if (!user.value.phoneNumber) return;
  
  // 验证手机号格式
  if(user.value.phoneNumber.length !== 11 || !/^\d+$/.test(user.value.phoneNumber)){
    phoneError.value = "手机号码格式不正确！请输入11位数字";
    return;
  }
  
  // 清除错误提示
  phoneError.value = "";
  
  try {
    // 使用正确的API方法检查手机号是否已注册
    await userApi.checkPhoneNumber(user.value.phoneNumber);
    console.log("手机号可用");
  } catch (error) {
    console.error("检查手机号出错:", error);
    // 如果是409冲突错误，说明手机号已存在
    if (error.message && (error.message.includes("409") || error.message.includes("已被注册"))) {
      phoneError.value = "该手机号已被注册，请使用其他手机号";
    }
  }
};

// 检查用户名是否已存在
const checkUsername = async () => {
  if (!user.value.username) return;
  
  // 清除错误提示
  usernameError.value = "";
  
  try {
    // 使用API方法检查用户名是否已注册
    await userApi.checkUsername(user.value.username);
    console.log("用户名可用");
  } catch (error) {
    console.error("检查用户名出错:", error);
    // 如果是409冲突错误，说明用户名已存在
    if (error.message && (error.message.includes("409") || error.message.includes("已被注册"))) {
      usernameError.value = "该用户名已被注册，请使用其他用户名";
    }
  }
};

const register = async () => {
  // 表单验证
  if (!user.value.username) {
    usernameError.value = "用户名不能为空！";
    return;
  }
  if (!user.value.phoneNumber) {
    phoneError.value = "手机号码不能为空！";
    return;
  }
  if (!user.value.password) {
    alert("密码不能为空！");
    return;
  }
  if (user.value.password !== confirmPassword.value) {
    alert("两次输入的密码不一致！");
    return;
  }
  
  // 验证手机号格式
  if(user.value.phoneNumber.length !== 11 || !/^\d+$/.test(user.value.phoneNumber)){
    phoneError.value = "手机号码格式不正确！请输入11位数字";
    return;
  }

  // 检查是否同意用户协议
  if (!agreeTerms.value) {
    alert("请阅读并同意用户协议和隐私政策");
    return;
  }
  
  // 准备注册数据，正确构造authorities
  const registerData = {
    ...user.value,
    // 构造Authority对象的集合
    authorities: [
      { name: "USER" }  // 必须使用对象格式，与后端Authority类匹配
    ],
    // 其他可能需要的信息
    sex: userSex.value
  };

  try {
    isLoading.value = true; // 显示加载状态
    
    // 调用API进行注册
    await userApi.register(registerData);
    alert("注册成功！请使用手机号和密码登录");
    router.push("/login");
  } catch (error) {
    console.error("注册请求出错:", error);
    
    // 根据错误信息提供更具体的提示
    if (error.message && error.message.includes("用户名") && error.message.includes("已被注册")) {
      usernameError.value = "用户名已被注册，请更换用户名";
    } else if (error.message && error.message.includes("手机号") && error.message.includes("已被注册")) {
      phoneError.value = "手机号已被注册，请更换手机号";
    } else {
      // 其他类型的错误
      alert(error.message || "注册失败，请稍后重试");
    }
  } finally {
    isLoading.value = false; // 结束加载状态
  }
};

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding-bottom: 14vw; /* 为底部Footer留出空间 */
}

/* 顶部图标区域 */
.register-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 8vw 0;
  text-align: center;
  background: linear-gradient(135deg, #0097ff, #00b2ff);
  color: white;
  border-radius: 0 0 15px 15px;
  box-shadow: 0 4px 10px rgba(0, 151, 255, 0.3);
  margin-bottom: 6vw;
}

.logo {
  width: 16vw;
  height: 16vw;
  object-fit: contain;
  margin-bottom: 2vw;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.register-header h1 {
  font-size: 5.5vw;
  margin: 0;
  font-weight: 600;
}

.subtitle {
  font-size: 3.2vw;
  opacity: 0.9;
  margin-top: 0.5vw;
}

/* 注册表单区域 */
.register-form {
  width: 85%;
  margin: 0 auto;
  padding: 5vw;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 3.5vw;
}

.input-with-icon {
  position: relative;
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  overflow: hidden;
}

.input-with-icon i {
  padding: 0 3vw;
  color: #0097ff;
  font-size: 5vw;
}

.form-input {
  border: none;
  outline: none;
  background-color: transparent;
  width: 100%;
  padding: 3vw 3vw 3vw 0;
  font-size: 3.5vw;
}

.gender-group {
  display: flex;
  align-items: center;
}

.gender-label {
  font-size: 3.5vw;
  color: #555;
  margin-right: 3vw;
}

.gender-options {
  display: flex;
  gap: 5vw;
}

.gender-option {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
}

.gender-option input[type="radio"] {
  position: absolute;
  opacity: 0;
}

.radio-button {
  display: inline-block;
  width: 4vw;
  height: 4vw;
  border: 2px solid #0097ff;
  border-radius: 50%;
  margin-right: 2vw;
  position: relative;
}

.gender-option input[type="radio"]:checked + .radio-button::after {
  content: '';
  position: absolute;
  width: 2.5vw;
  height: 2.5vw;
  background-color: #0097ff;
  border-radius: 50%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.radio-label {
  font-size: 3.5vw;
  color: #555;
}

.error-message {
  color: #ff3b30;
  font-size: 2.8vw;
  margin-top: 1vw;
  padding-left: 1vw;
}

.register-button {
  width: 100%;
  padding: 3.5vw;
  background: linear-gradient(90deg, #0097ff, #00b2ff);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 4vw;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 4vw;
}

.register-button:active {
  transform: scale(0.98);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.loading-spinner {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  100% {
    transform: rotate(360deg);
  }
}

.login-link {
  text-align: center;
  margin-top: 3vw;
  font-size: 3.2vw;
  color: #666;
}

.login-button {
  color: #0097ff;
  text-decoration: none;
  font-weight: 600;
  margin-left: 1vw;
  cursor: pointer;
}

/* 用户协议 */
.agreement {
  width: 85%;
  margin: 4vw auto;
  font-size: 2.8vw;
  color: #666;
  display: flex;
  align-items: center;
}

.agreement input[type="checkbox"] {
  margin-right: 2vw;
}

.agreement a {
  color: #0097ff;
  text-decoration: none;
}

/* 响应式调整 */
@media (min-width: 768px) {
  .register-form {
    max-width: 450px;
  }
  
  .agreement {
    max-width: 450px;
  }
}
</style>